package com.zhdl.hardware.plc.siemens.service.impl;

import com.zhdl.common.ytools.callback.CommonCallback;
import com.zhdl.hardware.plc.siemens.repository.impl.SiemensPortCmdHandleDaoImpl;
import com.zhdl.hardware.plc.siemens.service.SiemensCmdSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Slf4j
@Service
public class SiemensCmdSendServiceImpl implements SiemensCmdSendService {

    @Resource
    public SiemensPortCmdHandleDaoImpl handleDao;

    @Resource
    public ThreadPoolTaskScheduler taskScheduler1;

    Map<String, ScheduledFuture<?>> mapSF = new HashMap<>();

    /**
     * 读取plc寄存器值
     *
     * @param port     网口IP
     * @param address  寄存器地址
     * @param count    寄存器个数
     * @param callback 回调
     */
    @Override
    public void siemensAddressValue(String port, String address, int count, CommonCallback<String> callback) {
        taskScheduler1.scheduleWithFixedDelay(() -> {
            handleDao.raedValueByAddress(port, address, count, callback);
            log.info("当前读取的IP为:" + port + ",寄存器地址为:" + address + ",个数为:" + count);
        }, 3000);
    }

    /**
     * 写入plc的值
     *
     * @param port    网口IP
     * @param address 寄存器地址
     * @param value   寄存器值
     */
    @Override
    public void siemensWriteValue(String port, String address, String value) {
        handleDao.writeValueByAddress(port, address, value);
        log.info("当前写入的IP为:" + port + ",寄存器地址为:" + address + ",寄存器值为:" + value);
    }
}
